<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="68px"
    >
          <el-form-item label="申请员工" prop="userId">
            <UserSelect
                v-model="queryParams.userId"
                @node-change="handleUserSelect"
                class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="费用类型" prop="expenseType">
            <el-select
                v-model="queryParams.expenseType"
                placeholder="请选择费用类型"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.OA_EXPENSE_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="付款方式" prop="payMethod">
            <el-select
                v-model="queryParams.payMethod"
                placeholder="请选择付款方式"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.OA_PAY_METHOD)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
              <el-form-item label="付款日期" prop="payDate">
                <el-date-picker
                    v-model="queryParams.payDate"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    class="!w-220px"
                />
              </el-form-item>

          <el-form-item label="审批结果" prop="status">
            <el-select
                v-model="queryParams.status"
                placeholder="请选择审批结果"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button 
          v-hasPermi="['oa:payment:export']" 
          :loading="exportLoading" 
          plain 
          type="success" 
          @click="handleExport"
        >
          <Icon class="mr-5px" icon="ep:download" />
          导出
        </el-button>
            </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
    <!-- <el-table-column label="序号" align="center" prop="id" width="60" /> -->
    <el-table-column label="付款编号" align="center" prop="payCode" min-width="200" />
    <el-table-column label="申请员工" align="center" prop="userName" width="100" />
    <el-table-column label="申请部门" align="center" prop="deptName" width="120" />
    <el-table-column label="费用名称" align="center" prop="expenseName" width="100">
      <template #default="scope">
        <dict-tag :type="scope.row.expenseType" :value="scope.row.expenseName" />
      </template>
    </el-table-column>
    <el-table-column label="费用类型" align="center" prop="expenseType" width="100">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.OA_EXPENSE_TYPE" :value="scope.row.expenseType" />
      </template>
    </el-table-column>
    <el-table-column label="付款公司" align="center" prop="payCompany" width="350" />
    <el-table-column label="付款方式" align="center" prop="payMethod" width="100">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.OA_PAY_METHOD" :value="scope.row.payMethod" />
      </template>
    </el-table-column>
    <el-table-column label="支付状态" align="center" prop="payStatus" width="90">
      <template #default="scope">
        <span v-if="scope.row.payStatus === 1">已支付</span>
          <span v-else-if="scope.row.payStatus === 2">已取消</span>
          <span v-else>未支付</span>
      </template>
    </el-table-column>
    <el-table-column label="付款日期" align="center" prop="payDate" :formatter="dateFormatter2" width="110" />
    <el-table-column label="付款金额" align="center" prop="payAmount" width="110" />
    <el-table-column label="收款人" align="center" prop="receiverName" width="120" />
    <el-table-column label="有无发票" align="center" prop="hasInvoice" width="90">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.OA_IS_OR_NO" :value="scope.row.hasInvoice" />
      </template>
    </el-table-column>
    <!-- <el-table-column label="发票金额" align="center" prop="invoiceAmount" width="110" /> -->
    <el-table-column label="审批结果" align="center" prop="status" width="110">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="scope.row.status" />
      </template>
    </el-table-column>
    <el-table-column label="备注" align="center" prop="remark" min-width="200" />
    <el-table-column label="创建者" align="center" prop="creatorName" width="100" />
    <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        min-width="160"
    />
    <el-table-column label="操作" align="center" min-width="180" fixed="right">
      <template #default="scope">
        <el-button
          link
          type="primary"
          @click="handleView(scope.row)"
        >
          查看
        </el-button>
      </template>
    </el-table-column>
  </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

  <DetailDrawer
    v-model="showDetailDrawer"
    :task-id="currentExpenseId"
    title="付款详情" />

  <!-- 详情弹窗 -->
  <el-dialog
    v-model="showDetailDialog"
    title="付款详情"
    width="800px"
    :close-on-click-modal="false"
  >
    <PaymentDetail :id="currentDetailId" />
  </el-dialog>

  <ProcessInstanceDetailDrawer
    v-model="showDrawer" :process-instance-id="currentProcessInstanceId" title="流程进度"
    @success="handleDrawerSuccess" />
</template>

<script lang="ts" setup>
  import { DICT_TYPE, getIntDictOptions ,getStrDictOptions} from '@/utils/dict'
  import { dateFormatter,dateFormatter2 } from '@/utils/formatTime'
  import { PaymentApi, PaymentVO } from '@/api/oa/payment'
  import * as ProcessInstanceApi from '@/api/bpm/processInstance'
  import UserSelect from '@/views/system/user/UserSelect.vue'
  import ProcessInstanceDetailDrawer from '@/views/bpm/processInstance/components/ProcessInstanceDetailDrawer.vue'
  import DetailDrawer from '@/views/oa/payment/components/DetailDrawer.vue'
  import PaymentDetail from '@/views/oa/payment/detail.vue'
  import download from '@/utils/download'
  defineOptions({ name: 'Payment' })

  const message = useMessage() // 消息弹窗
  const router = useRouter() // 路由
  const { t } = useI18n() // 国际化

  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const list = ref([]) // 列表的数据
  const queryParams = reactive({
      pageNo: 1,
    pageSize: 10,
    userId: undefined,
    title: undefined,
    expenseType: undefined,
    payMethod: undefined,
    payDate: [],
    receiverAccount: undefined,
    status: undefined,
    payStatus: 1,
  })
  const queryFormRef = ref() // 搜索的表单
  const showDetailDrawer = ref(false)
  const currentExpenseId = ref<number | undefined>(undefined)

  const showDrawer = ref(false)
  const currentProcessInstanceId = ref('')

  // 详情弹窗相关
  const showDetailDialog = ref(false)
  const currentDetailId = ref<number | undefined>(undefined)

  const exportLoading = ref(false) // 导出的加载中

  const handleDrawerSuccess = () => {
    showDrawer.value = false
    getList()
  }

  /** 查询列表 */
  const getList = async () => {
    loading.value = true
    try {
              const data = await PaymentApi.getPaymentPage(queryParams)
      list.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
  }

  /** 添加操作 */
  const handleCreate = () => {
    router.push({ name: 'PaymentCreate' })
  }

  /** 详情操作 */
  const handleDetail = (row: PaymentVO) => {
    currentExpenseId.value = row.id
    showDetailDrawer.value = true
  }

  /** 查看详情操作 */
  const handleView = (row: PaymentVO) => {
    currentDetailId.value = row.id
    showDetailDialog.value = true
  }

  /** 取消请假操作 */
  const cancelProcess = async (row) => {
    // 二次确认
    const { value } = await ElMessageBox.prompt('请输入取消原因', '取消流程', {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
      inputErrorMessage: '取消原因不能为空'
    })
    // 发起取消
    await ProcessInstanceApi.cancelProcessInstanceByStartUser(row.id, value)
    message.success('取消成功')
    // 刷新列表
    await getList()
  }
  const handleUserSelect = (val) =>{
    queryParams.userId = val ? val.id : undefined
    console.log('queryParams.userId',queryParams.userId)
  }
  /** 审批进度 */
  const handleProcessDetail = (row) => {
    currentProcessInstanceId.value = row.processInstanceId
    showDrawer.value = true
  }

  /** 导出按钮操作 */
  const handleExport = async () => {
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await PaymentApi.exportPayment(queryParams)
      download.excel(data, '付款支出.xls')
    } catch {
    } finally {
      exportLoading.value = false
    }
  }

  // fix: 列表不刷新的问题。
  watch(
      () => router.currentRoute.value,
      () => {
        getList()
      }
  )

  /** 初始化 **/
  onMounted(() => {
    getList()
  })
</script>
